package cn.cyh.queue_service.controller;

import cn.cyh.queue_service.common.Result;
import cn.cyh.queue_service.model.dto.StatisticsRequest;
import cn.cyh.queue_service.model.dto.StatisticsResponse;
import cn.cyh.queue_service.service.StatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/statistics")
@RequiredArgsConstructor
@Tag(name = "统计数据接口", description = "用于获取和导出统计数据")
@Slf4j
public class StatisticsController {

    private final StatisticsService statisticsService;

//    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    @GetMapping("/daily")
    @Operation(summary = "获取每日统计数据", description = "根据日期获取每日统计数据，可选择性根据业务类型筛选")
    public Result<List<StatisticsResponse>> getDailyStatistics(
            @Parameter(description = "统计日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
            @Parameter(description = "业务类型ID，可选参数")
            @RequestParam(required = false) Long serviceTypeId) {
        log.info("获取日期 {} 的每日统计数据，业务类型ID: {}", date, serviceTypeId);
        return Result.success(statisticsService.getDailyStatistics(date, serviceTypeId));
    }

    @PostMapping("/range")
    @Operation(summary = "获取日期范围内的统计数据", description = "根据日期范围和筛选条件获取统计数据")
//    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    public Result<List<StatisticsResponse>> getStatistics(@RequestBody StatisticsRequest request) {
        log.info("获取从 {} 到 {} 的统计数据", request.getStartDate(), request.getEndDate());
        return Result.success(statisticsService.getStatistics(request));
    }

    @GetMapping("/by-business-type")
    @Operation(summary = "按业务类型获取统计数据", description = "获取日期范围内按业务类型分组的统计数据")
//    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    public Result<Collection<StatisticsResponse>> getStatisticsByBusinessType(
            @Parameter(description = "开始日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取从 {} 到 {} 按业务类型分组的统计数据", startDate, endDate);
        Collection<StatisticsResponse> values = statisticsService.getStatisticsByBusinessType(startDate, endDate).values();
        return Result.success(values);
    }

    @GetMapping("/by-window")
    @Operation(summary = "按窗口获取统计数据", description = "获取日期范围内按窗口分组的统计数据")
    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    public Result<Map<Long, StatisticsResponse>> getStatisticsByWindow(
            @Parameter(description = "开始日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        log.info("获取从 {} 到 {} 按窗口分组的统计数据", startDate, endDate);
        return Result.success(statisticsService.getStatisticsByWindow(startDate, endDate));
    }

    @GetMapping("/current")
    @Operation(summary = "获取实时统计数据", description = "获取当日实时统计数据，从队列记录计算")
//    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER', 'STAFF')")
    public Result<StatisticsResponse> getCurrentStatistics() {
        log.info("获取当前实时统计数据");
        return Result.success(statisticsService.getCurrentStatistics());
    }

    @PostMapping("/generate")
    @Operation(summary = "生成每日统计数据", description = "手动触发生成指定日期的统计数据")
    public Result<Integer> generateDailyStatistics(
            @Parameter(description = "统计日期，格式yyyy-MM-dd")
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        log.info("手动生成日期 {} 的统计数据", date);
        return Result.success(statisticsService.generateDailyStatistics(date));
    }

    @PostMapping("/export/csv")
    @Operation(summary = "导出CSV格式统计数据", description = "将统计数据导出为CSV格式")
    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    public ResponseEntity<String> exportStatisticsToCSV(@RequestBody StatisticsRequest request) {
        log.info("导出从 {} 到 {} 的CSV格式统计数据", request.getStartDate(), request.getEndDate());
        String csvData = statisticsService.exportStatisticsToCSV(request);
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=statistics.csv")
                .contentType(MediaType.parseMediaType("text/csv"))
                .body(csvData);
    }

    @PostMapping("/export/excel")
    @Operation(summary = "导出Excel格式统计数据", description = "将统计数据导出为Excel格式")
    @PreAuthorize("hasAnyRole('ADMIN', 'MANAGER')")
    public ResponseEntity<byte[]> exportStatisticsToExcel(@RequestBody StatisticsRequest request) {
        log.info("导出从 {} 到 {} 的Excel格式统计数据", request.getStartDate(), request.getEndDate());
        byte[] excelData = statisticsService.exportStatisticsToExcel(request);
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=statistics.xlsx")
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                .body(excelData);
    }
} 